<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
function api_json($data=[], $code=null, $message=null, $httpCode=200)
{

    $code = !isset($code) ? EC_OK : $code;
    $message = !isset($message) ? get_error_message($code) : $message;
    $data = [
        'code'      =>  $code,
        'message'   =>  $message,
        'data'      =>  $data,
    ];

    return json($data, $httpCode);
}

function get_error_message($word)
{
    $code = config('code.');

    return isset($code[$word]) ? $code[$word] : '';
}

function get_rand_num($length)
{
    $randStr = null;
    $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($str) - 1;

    for ($i = 0; $i < $length; $i++) {
        $randStr .= $str[rand(0, $max)];
    }

    return $randStr;
}

/**
 * 发送HTTP请求方法
 *
 * @param  string $url 请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 *
 *@return array  $data   响应数据
 */
function curl_http_request($url, $params, $method = 'GET', $header='', $multi = false)
{
    $header = $header ? $header : array('User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36');
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header
    );

    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)) {
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }

    //写请求日志
//    if (config('app_debug')) {
        //写日志
//    }

    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) {
        throw new Exception('请求发生错误：' . $error);
    }

    return  $data;
}